import { MutationTree } from "vuex";
import storage from "store";
import { objEncodeToStr, strDecodeToObj } from "/@/util/util";
import { MutationTypes } from "./mutation-types";
import { UserInfo } from "./types";
import { initUserInfo } from "./state";
import { RootState } from "../types";

export type Mutations<S = RootState> = {
  [MutationTypes.SET_ACCESS_TOKEN](state: S, payload: string): void;
  [MutationTypes.GET_ACCESS_TOKEN](state: S): void;
  [MutationTypes.SET_USER_INFO](state: S, payload: UserInfo): void;
  [MutationTypes.GET_USER_INFO](state: S): void;
  [MutationTypes.CLEAR_USER_INFO](state: S): void;
};

export const userMutations: MutationTree<RootState> & Mutations = {
  [MutationTypes.SET_ACCESS_TOKEN](state, payload) {
    state.accessToken = payload;
    storage.set(MutationTypes.SET_ACCESS_TOKEN, payload);
  },
  [MutationTypes.GET_ACCESS_TOKEN](state) {
    const accessToken = storage.get(MutationTypes.SET_ACCESS_TOKEN);
    state.accessToken = accessToken;
  },
  [MutationTypes.SET_USER_INFO](state, payload) {
    // 设置为已登录状态
    payload.isLogin = true;
    state.userInfo = payload;
    const storeData = objEncodeToStr(state.userInfo);
    storage.set(MutationTypes.SET_USER_INFO, storeData);
  },
  [MutationTypes.CLEAR_USER_INFO](state) {
    state.userInfo = initUserInfo();
    state.accessToken = "";
    const storeData = objEncodeToStr(state.userInfo);
    storage.set(MutationTypes.SET_USER_INFO, storeData);
    storage.set(MutationTypes.SET_ACCESS_TOKEN, state.accessToken);
  },
  [MutationTypes.GET_USER_INFO](state) {
    const storeData = storage.get(MutationTypes.SET_USER_INFO, objEncodeToStr(initUserInfo()));
    const payload = strDecodeToObj(storeData);
    state.userInfo = payload;
  },
};
